package com.tuxing.draa_data.util.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.tuxing.draa_data.pojo.DraaTemporaryJournal;
import com.tuxing.draa_data.service.draa.DraaJournalService;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

/**
 * @author YuanShiHang
 * @version 1.0
 * @className DraaDataListener
 * @description 基础描述:Excel监听类
 * @date 2021/11/16 10:49
 */
@Slf4j
public class DraaJournalDataListener implements ReadListener<DraaTemporaryJournal> {

    /**
     * 将spring管理的bean当做参数，利用构造方法进行注入
     * 因为ReadListener不支持spring的bean采用@Autowired和@resource注入
     */
    private DraaJournalService draaDataService;

    public DraaJournalDataListener(DraaJournalService draaDataService) {
        this.draaDataService = draaDataService;
    }

    /**
     * 每隔1000条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    /**
     * 缓存的数据
     */
    private List<DraaTemporaryJournal> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(DraaTemporaryJournal draaExcelDto, AnalysisContext analysisContext) {

        log.info("解析到一条数据:{}", JSON.toJSON(draaExcelDto));
        cachedDataList.add(draaExcelDto);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        try {
            draaDataService.saveBatch(cachedDataList);
        } catch (Exception ex) {
            log.error("数据保存失败，失败原因：" + ex.getMessage(), ex);
        }

        log.info("存储数据库成功！");
    }
}
